package com.programmercarl.array;

import java.util.Map;

/**
 * https://leetcode.cn/problems/minimum-size-subarray-sum/
 *
 * @author yulongtian
 * @create 2024-12-11 9:41
 */
public class Test11 {
    public static void main(String[] args) {
//        int[] nums = {1, 2, 3, 4, 5};
        int[] nums = {1, 1, 1, 1, 1, 1, 1, 1};
        int target = 11;
        System.out.println(minSubArrayLen(target, nums));
    }

    /**
     * 双指针 AC
     *
     * @param target
     * @param nums
     * @return
     */
    public static int minSubArrayLen(int target, int[] nums) {
        int res = Integer.MAX_VALUE;
        int slowPointer = 0, fastPointer = 0;
        int temp_sum = 0;
        while (fastPointer < nums.length) {
            while (fastPointer < nums.length && temp_sum < target) {
                temp_sum += nums[fastPointer];
                fastPointer++;
            }
            while (slowPointer <= fastPointer && temp_sum >= target) {
                res = Math.min(res, fastPointer - slowPointer);
                temp_sum -= nums[slowPointer];
                slowPointer++;
            }
        }
        return res == Integer.MAX_VALUE ? 0 : res;
    }

    /**
     * 暴力超时
     *
     * @param target
     * @param nums
     * @return
     */
    public static int minSubArrayLen01(int target, int[] nums) {
        int res = Integer.MAX_VALUE;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] >= target) {
                res = 1;
                return res;
            }
            int temp_sum = nums[i];
            for (int j = i + 1; j < nums.length; j++) {
                temp_sum += nums[j];
                if (temp_sum >= target) {
                    res = Math.min(res, j - i + 1);
                }
            }
        }
        return res == Integer.MAX_VALUE ? 0 : res;
    }
}
